<template>
  <div class="home">
    <img alt="Vue logo" src="../../assets/logo.png" />
    <div class="login-container">
      <h2>用户登录</h2>
      <div class="form-group">
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" />
      </div>
      <div class="form-group">
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="password" />
      </div>
      <button @click="handleLogin">登录</button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import { useUserStore } from "@/store/user";
import { useRouter } from "vue-router";

export default defineComponent({
  name: "UserLogin",
  setup() {
    const userStore = useUserStore();
    const router = useRouter();
    const username = ref("");
    const password = ref("");

    const handleLogin = async () => {
      if (username.value && password.value) {
        try {
          const success = await userStore.login(username.value, password.value);
          if (success) {
            alert("登录成功");
            // 登录成功后可以跳转到其他页面
            // router.push('/dashboard');
          } else {
            alert("登录失败，请检查用户名和密码");
          }
        } catch (error: any) {
          alert("登录出错：" + (error.message || "未知错误"));
        }
      } else {
        alert("请输入用户名和密码");
      }
    };

    return {
      username,
      password,
      handleLogin,
    };
  },
});
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
.form-group {
  margin-bottom: 15px;
}
.form-group label {
  display: block;
  margin-bottom: 5px;
}
.form-group input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}
button {
  padding: 10px 15px;
  background-color: #4caf50;
  color: white;
  border: none;
  cursor: pointer;
}
</style>
